#include "capturesignal.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>
#include <QDebug>


//#define linux
int CaptureSignal::sigintFd[2];//类内声明，类外初始化


CaptureSignal::CaptureSignal(QObject *parent) : QObject(parent)
{
//#if defined linux
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
       qFatal("Couldn't create INT socketpair");
    snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
    connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));
//#endif
}

void CaptureSignal::getObject(ClientManager *object)
{
    obj = object;
}

int CaptureSignal::setup_unix_signal_handlers()
{
//#if defined linux
    struct sigaction interrupt;

    interrupt.sa_handler = CaptureSignal::intSignalHandler;
    sigemptyset(&interrupt.sa_mask);
    interrupt.sa_flags = 0;
    interrupt.sa_flags |= SA_RESTART;

    if (sigaction(SIGINT, &interrupt, nullptr))
       return 1;
//#endif
}


void CaptureSignal::intSignalHandler(int unused)
{
    char a = 1;
    write(sigintFd[0], &a, sizeof(a));

}

void CaptureSignal::handleSigInt()
{
    snInt->setEnabled(false);
        char tmp;
        read(sigintFd[1], &tmp, sizeof(tmp));
        //在此处做想要做的操作
        obj->closeOutput();
        snInt->setEnabled(true);
}

